/**
 * 树形选择组件
 */
import React, { Component ,Fragment} from 'react';
import { Tree, Spin, Popover, Divider, TreeSelect,Tooltip, Popconfirm ,Icon } from 'antd';
import { isEmpty ,doActionHandler,ajax,buildTreeNodes,getLocalMessage} from '../common';

import UIIcon from './UIIcon';

const TreeNode = Tree.TreeNode;

export default class UIDataTreeSelect extends Component {

	constructor(props) {
		super(props);
		
		let treeDataUrl = null;

		if (props.pathValue != null) {
			treeDataUrl = props.dataUrl + '/' + props.pathValue + '/';
		}
		else {
			treeDataUrl = props.dataUrl;
		}

		this.state = {
            loading: false,
            treeDataUrl : treeDataUrl,
			treeData: [],
			selectedNodeIds: [],
			expandedNodeIds: [],
			nodeActions: {},
		};
    }
    
    componentDidMount(){
        const {treeDataUrl,expandLevel,expandedNodeIds} = this.state;

        buildTreeNodes(treeDataUrl, { expandLevel: expandLevel }, (subNodes) => {
            this.setState({treeData : subNodes});
            this.getDefaultExpandNodeIds(subNodes, expandedNodeIds);
        });
    }

	getDefaultExpandNodeIds = (subNodes, expandedTreeNodeIds) => {
		for (var i = 0; i < subNodes.length; i++) {
			if (subNodes[i].expanded === true) {
				expandedTreeNodeIds.push(subNodes[i].id);
			}
			if (subNodes[i].nodes && subNodes[i].nodes.length > 0) {
				this.getDefaultExpandNodeIds(subNodes[i].nodes, expandedTreeNodeIds);
			}
		}
	}

	loadData = () => {
		
        const {treeDataUrl,expandLevel} = this.state;

        const expandedTreeNodeIds = [];

        this.setState({ loading: true, nodeActions: {} });

        const treeParams = { expandLevel: expandLevel };

        buildTreeNodes(treeDataUrl, { ...treeParams }, (subNodes) => {
            this.getDefaultExpandNodeIds(subNodes, expandedTreeNodeIds);
            
            this.setState({ treeData: subNodes, loading: false, expandedNodeIds: [...expandedTreeNodeIds]});
        });
	}

	onLoadData = (treeNode) => {

		const { selectedNodeIds,treeDataUrl,expandLevel } = this.state;
		
		return new Promise((resolve) => {

			setTimeout(() => {
				const parentNode = treeNode.props.dataRef;
				const expandedNodeIds = [];

				buildTreeNodes(treeDataUrl, { n_level: parentNode.level, expandLevel: this.props.expandLevel, nodeid: parentNode.id, nodeConfigId: parentNode.nodeConfigId, selectedNodeId: selectedNodeIds },  (subNodes) => {
                    parentNode.nodes = subNodes;
                    for (let i = 0; i < subNodes.length; i++) {
						if (subNodes[i].expanded === true) {
							expandedNodeIds.push(subNodes[i].id);
						}
                    }
                    
                    this.setState({
                        treeData: [...this.state.treeData],
                        expandedNodeIds: [...expandedNodeIds],
                    });

                    resolve();
				});
				//console.log(expandedNodeIds);
				
			});
		});
	}

	onTreeNodeSelect = (selectedKeys, e) => {
        
		if (e.selected === false) {
			return;
		}
		this.setState({ selectedNodeIds: selectedKeys });
		const { node } = e;
		if (this.props.onSelectChange !== undefined) {
			this.props.onSelectChange(selectedKeys, node);
		}
	}

	getSelectedNodeIds = () => {
		return this.state.selectedNodeIds;
	}

	clearSelectedNodeIds = () => {
		this.setState({ selectedNodeIds: [] });
	}

	handleNodeAction = (nodeAction, node) => {
		const { history, actionHandler, parent } = this.props;
		const actionEvent = {
			actionId: nodeAction.actionId,
			action: nodeAction.handler,
			component: parent != null ? parent : this,
			params: node
		};
		if (actionHandler) {
			if (nodeAction.handler.startsWith('/') && history) {
				history.push(nodeAction.handler, node);
			}
			else {
				doActionHandler(actionEvent, actionHandler(actionEvent));
			}
		}
	}

	onNodeExpand = (expandedKeys, expanded, node) => {
		this.setState({ expandedNodeIds: expandedKeys });
	}

	renderTreeNodes = (data) => {
		const { renderTreeNode ,currentModule} = this.props;
		const { nodeActions } = this.state;
		var owner = this;
		return data.map((item) => {
			var nodeTitle = null;
			var nodeAction = null;
			if (item.actionGroupId) {
				if (item.actionGroupId in nodeActions) {
					nodeAction = nodeActions[item.actionGroupId];
				}
				else if(currentModule !== undefined){
					
					ajax('SYSTEM/auth/getUserActionGroupBean', { modelId: currentModule.menuId, actionGroupId: item.actionGroupId }, function (actionGroup) {
						var cellActions = [];
						actionGroup.actionBeans.map(function (nodeAction, index, arr) {
							var cellActionLink = null;
							if (isEmpty(nodeAction.desc) === false) {
								cellActionLink = <Tooltip mouseLeaveDelay={0} title={nodeAction.desc}>{isEmpty(nodeAction.confirmInfoKey) ? <a onClick={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{nodeAction.label}</a> : <a>{nodeAction.label}</a>}{index < arr.length - 1 ? <Divider type="vertical" /> : ''}</Tooltip>
							}
							else {
								cellActionLink = <Fragment>{isEmpty(nodeAction.confirmInfoKey) ? <a onClick={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{nodeAction.label}</a> : <a>{nodeAction.label}</a>}{index < arr.length - 1 ? <Divider type="vertical" /> : ''}</Fragment>
							}

							if (isEmpty(nodeAction.confirmInfoKey) === false) {
								cellActions.push(<Popconfirm title={getLocalMessage(nodeAction.confirmInfoKey)} onConfirm={owner.handleNodeAction.bind(owner, { actionId: nodeAction.id, handler: nodeAction.handler }, item)}>{cellActionLink}</Popconfirm>);
							}
							else {
								cellActions.push(<Fragment>{cellActionLink}</Fragment>);
							}
						});
						nodeAction = (<Popover placement="bottom" content={cellActions} ><Icon type="setting" /></Popover>);
						nodeActions[item.actionGroupId] = nodeAction;
						owner.setState(nodeActions);
					});
				}
			}
			if (renderTreeNode) {
				nodeTitle = (<span><UIIcon icon={item.icon} ></UIIcon> {renderTreeNode(item)} {nodeAction}</span>);
			}
			else {
				nodeTitle = (<span><UIIcon icon={item.icon} ></UIIcon> {item.text} {nodeAction}</span>);
			}
			if (item.nodes && item.nodes.length > 0) {
				return (
					<TreeNode title={nodeTitle} key={item.id} value={item} isLeaf={item.isLeaf} dataRef={item}>
						{this.renderTreeNodes(item.nodes)}
					</TreeNode>
				);
			}
			else {
				return <TreeNode title={nodeTitle} key={item.id} value={item} isLeaf={item.isLeaf} dataRef={item} />;
			}

		});
	}

	render() {

		return (
			<Spin spinning={this.state.loading}>
				<TreeSelect {...this.props} loadData={this.onLoadData} showIcon={false}
					defaultExpandedKeys={this.state.expandedNodeIds}
					getPopupContainer={trigger => trigger.parentNode}
					defaultExpandAll={this.props.expandLevel === -1}
					onSelect={this.onTreeNodeSelect}
					onExpand={this.onNodeExpand}
				>
					{this.renderTreeNodes(this.state.treeData)}
				</TreeSelect>
			</Spin >
		);
	}
}
